Skip to main content

Composite

It allow you to treat individual objects and compositions of objects uniformly. It is useful when you have to work with tree-like hierarchical structures, where individual objects (leaf nodes) and compositions of objects (composite nodes) are part of the same hierarchy.

Structure

  • Component: This is the interface or abstract class that declares the operations common to both leaf and composite nodes.
  • Leaf: Represents individual objects that cannot have children. It implements the Component interface.
  • Composite: Represents objects that can contain other Component objects (both leaf and composite). It implements the Component interface and contains methods for adding, removing, and managing child components

Example

import java.util.ArrayList;
import java.util.List;

// Component interface
interface FileSystemComponent {
void showDetails();
}

// Leaf class: File
class File implements FileSystemComponent {
private String name;

public File(String name) {
this.name = name;
}

@Override
public void showDetails() {
System.out.println("File: " + name);
}
}

class Folder implements FileSystemComponent {
private String name;
private List<FileSystemComponent> components = new ArrayList<>();

public Folder(String name) {
this.name = name;
}

// Adding a new component (File or Folder)
public void addComponent(FileSystemComponent component) {
components.add(component);
}

// Removing a component
public void removeComponent(FileSystemComponent component) {
components.remove(component);
}

// Show details of the folder and its contents
@Override
public void showDetails() {
System.out.println("Folder: " + name);
for (FileSystemComponent component : components) {
component.showDetails();
}
}
}

public class Main {
public static void main(String[] args) {
// Creating individual files (leaf nodes)
FileSystemComponent file1 = new File("File1.txt");
FileSystemComponent file2 = new File("File2.txt");
FileSystemComponent file3 = new File("File3.jpg");

// Creating folders (composite nodes)
Folder folder1 = new Folder("Documents");
Folder folder2 = new Folder("Images");

// Adding files to folders
folder1.addComponent(file1); // Adding file1 to Documents
folder1.addComponent(file2); // Adding file2 to Documents
folder2.addComponent(file3); // Adding file3 to Images

// Creating the root folder and adding sub-folders
Folder rootFolder = new Folder("Root");
rootFolder.addComponent(folder1); // Adding Documents folder to Root
rootFolder.addComponent(folder2); // Adding Images folder to Root

// Displaying the file system structure
rootFolder.showDetails();
}
}